<template>
  <div class="add-product-wrapper">
    <el-form label-width="108px" :model="form" ref="form" :rules="rules">
      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>基本信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务中心" prop="shopId">

              <el-select placeholder="选择服务中心" v-model="form.shopId" style="width: 100%;" @change="shopChange" filterable>
                <el-option v-for="item in shopOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属分类" prop="goodsKind">
              <el-select placeholder="选择分类" v-model="form.goodsKind" style="width: 100%;">
                <el-option v-for="item in kindList" :key="item.id" :label="item.kindName"
                  :value="item.kindId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="库存单位" prop="inventoryUnit">
              <el-input v-model="form.inventoryUnit" placeholder="请输入库存单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起购数量" prop="buyMinNumber">
              <el-input v-model="form.buyMinNumber" type="number" placeholder="请输入起购数量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大数量" prop="buyMaxNumber">
              <el-input v-model="form.buyMaxNumber" type="number" placeholder="请输入最大数量"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      
        <el-row>
          <el-col :span="8">
            <el-form-item label="配送费用" prop="sendCharge">
              <el-input v-model="form.sendCharge" type="number" placeholder="请输入配送费用"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="包装费用" prop="pkgCharge">
              <el-input v-model="form.pkgCharge" type="number" placeholder="请输入包装费用"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="返回积分" prop="giveIntegral">
              <el-input v-model="form.giveIntegral" type="number" placeholder="请输入返回积分"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="商品品牌" prop="brandId">
              <brand-select v-model="form.brandId" @change="onBrandChange"></brand-select>
            </el-form-item>
          </el-col> -->



        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="餐饮类型">
              <el-radio-group v-model="form.mealType">
                <el-radio :label="0">早餐</el-radio>
                <el-radio :label="1">午餐</el-radio>
                <el-radio :label="2">晚餐</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="消费方式">
              <el-radio-group v-model="form.buyType" @change="changeBuy">
                <el-radio :label="0">自费</el-radio>
                <el-radio :label="1">免费</el-radio>
                <el-radio :label="2">面议</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="配送方式" prop="isAway">
              <el-radio-group v-model="form.isAway">
                <el-radio :label="0">店内消费</el-radio>
                <el-radio :label="1">送货上门</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="配送时段" prop="rangeTime">
              <el-time-picker v-model="rangeTime" is-range format="HH:mm" value-format="HH:mm" :style="{ width: '100%' }"
                start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上午时段" prop="rangeMorning">
              <el-time-picker v-model="rangeMorning" is-range format="HH:mm" value-format="HH:mm"
                :style="{ width: '100%' }" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="中午时段" prop="rangeNoon">
              <el-time-picker v-model="rangeNoon" is-range format="HH:mm" value-format="HH:mm" :style="{ width: '100%' }"
                start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下午时段" prop="rangeNight">
              <el-time-picker v-model="rangeNight" is-range format="HH:mm" value-format="HH:mm" :style="{ width: '100%' }"
                start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="全市服务">
              <el-radio-group v-model="form.isAll">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上架状态">
              <DictRadio v-model="form.isShelves" size="small" :radioData="dict.type.sys_online_status" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="产品标签" prop="tags">
            <tag-editor v-model="tags" :select="true"></tag-editor>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="产品描述" prop="goodsDesc">
            <el-input type="textarea" v-model="form.goodsDesc" rows="5" placeholder="请输入产品描述" />
          </el-form-item>
        </el-row>
      </el-card>

      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>产品图片</span>
        </div>
        <el-form-item label="主图" prop="coverImage">
          <oss-image-upload v-model="form.coverImage" :limit="1"></oss-image-upload>
        </el-form-item>
        <el-form-item label="轮播图" prop="albumPics">
          <goods-image-upload v-model="albumPics" :limit="5"></goods-image-upload>

        </el-form-item>
      </el-card>

      <el-card style="margin: 20px 20px; font-size: 14px" v-if="buyFlag">
        <div slot="header">
          <span>产品规格</span>
        </div>
        <el-form-item label="产品规格">
          <el-radio-group v-model="form.isExistManySpec">
            <el-radio :label="0">单规格</el-radio>
            <el-radio :label="1">多规格</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="规格类型">
          <div class="sku-wrapper">
            <div class="sku_sorts">
              <div class="sku_sort" v-for="(s, idx0) in goodsAttr" :key="s.name">
                <div class="label flex-center">
                  <div class="flex-one">
                    <!-- <dict-select v-model="s.name" prop-name="sku_sort_list" value-prop="label"
                      style="width:170px"></dict-select> -->
                  </div><a class="red" @click="deleteSkuSort(idx0)">删除规格类型</a>
                </div>
                <div class="values" v-if="s.name">
                  <div class="value" v-for="(it2, idx1) in s.options" :key="idx1">
                    <el-input :value="it2.name" @input="changeName(s, idx1, $event)" placeholder="请输入规格名称"></el-input><a
                      class="red no-break ml8"
                      v-if="(idx1 < s.options.length - 1 || (s.options.length === maxOptionNum &amp;&amp; idx1 === 3))"
                      @click="deleteOption(s, idx1)">删除</a>
                  </div>
                </div>
              </div>
            </div>
            <el-button v-if="goodsAttr.length < 2" @click="addSkuSort">+添加规格类型</el-button>
          </div>
        </el-form-item>
        <el-form-item label="规格信息">
          <el-button @click="refreshSku()" class="mb20">刷新列表</el-button>
          <el-table :data="form.skuList" :max-height="400">
            <el-table-column v-for="s in skuAttr" :label="s.name" :key="s.name" :prop="s.name"></el-table-column>
            <el-table-column label="展示图片">
              <template v-slot="{ row }">
                <oss-image-upload class="img-upload-mini" v-model="row.pic" :limit="1"
                  :is-show-tip="false"></oss-image-upload>
              </template>
            </el-table-column>
            <el-table-column label="销售价格(元)">
              <template v-slot="{ row, $index }">
                <el-form-item :rules="{ required: true, message: '请填写价格', trigger: 'blur' }"
                  :prop="'skuList[' + $index + '].price'">
                  <el-input v-model="row.price"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="库存">
              <template>
                <el-input v-model="row.inventory" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="重量(g)">
              <template>
                <el-input v-model="row.weight" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="原价(元)">
              <template>
                <el-input v-model="row.originalPrice" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="配送金额">
              <template>
                <el-input v-model="row.shareAccount" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="配送积分">
              <template>
                <el-input v-model="row.shareIntegral" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="SKU编码">
              <template v-slot="{ row }">
                <el-form-item>
                  <el-input v-model="row.coding"></el-input>
                  <el-input v-model="row.skuData" v-show="false"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-card>
      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>详情页</span>
        </div>
        <el-form-item label="移动端" prop="contentWeb">
          <Editor v-model="form.contentWeb" placeholder="请输入内容" type="url"></Editor>
        </el-form-item>
        <el-form-item label="PC端" prop="detailHtml">
          <Editor v-model="form.detailHtml" placeholder="请输入内容" type="url"></Editor>
        </el-form-item>

      </el-card>

      <div class="tc" id="footer-global">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
// import { delPmsProduct, getGoods, updateGoods, addGoods } from "@/api/goods/goods";
// import ProductCategorySelect from "@/views/components/ProductCategorySelect";
// import BrandSelect from "@/views/components/BrandSelect";
// import { listKind } from "@/api/goods/kind";
// import { getShopTree } from "@/api/shop/shop";

export default {
  name: "AddProduct",
  dicts: ['sys_online_status'],
  // components: { BrandSelect, ProductCategorySelect },
  data() {
    return {
      rules: {
        shopId: [
          { required: true, message: "中心ID不能为空", trigger: "blur" }
        ],
        goodsName: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        goodsKind: [
          { required: true, message: "商品类型不能为空", trigger: "blur" }
        ],
        disTime: [
          { required: true, message: "DIS_TIME不能为空", trigger: "blur" }
        ],
        bookType: [
          { required: true, message: "预约不能为空", trigger: "change" }
        ],
        buyType: [
          { required: true, message: "BUY_TYPE不能为空", trigger: "change" }
        ],
        mealType: [
          { required: true, message: "MEAL_TYPE不能为空", trigger: "change" }
        ],
        inventoryUnit: [
          { required: true, message: "库存单位不能为空", trigger: "blur" }
        ],
        isAll: [
          { required: true, message: "SEO关键字不能为空", trigger: "blur" }
        ],
        pkgCharge: [
          { required: true, message: "包装费用不能为空", trigger: "blur" }
        ],
        sendCharge: [
          { required: true, message: "配送费用不能为空", trigger: "blur" }
        ],
        buyMinNumber: [
          { required: true, message: "起购数量不能为空", trigger: "blur" }
        ],
        buyMaxNumber: [
          { required: true, message: "最大数量不能为空", trigger: "blur" }
        ],
        giveIntegral: [
          { required: true, message: "返回积分不能为空", trigger: "blur" }
        ],
      },
      form: {
        isShelves: 1,
        sort: 1000,
        isAll: 0,
        mealType: 0,
        isAway: 0,
        isExistManySpec: 0,
        buyType: 0,
        isExistManySpec: 0,
        buyMinNumber:1,
        buyMaxNumber:100,
        sendCharge:0,
        pkgCharge:0,
        giveIntegral:10
      },
      kindList: [],
      skuAttr: [],
      shopOptions: [],
      albumPics: null,
      goodsAttr: [
        {
          name: '默认',
          options: [
            { name: '默认' },
            { name: null }
          ]
        }
      ],
      rangeTime: ['08:00', '20:00'],
      rangeMorning: ['08:00', '09:30'],
      rangeNoon: ['12:00', '13:30'],
      rangeNight: ['19:00', '20:30'],
      tags: [],
      buyFlag: true,
      maxOptionNum: 44
    }
  },
  created() {
  //   const { id } = this.$route.query
  //   if (id) {
  //     this.getInfo(id);
  //   }else{
  //     this.refreshSku();
  //    }
  //    const { organId } = this.$route.query;
  //  this.getShopTree(organId);
  },
  methods: {
    refreshSku() {
      let skus = [];
      let skuMap = new Map()
      this.skuAttr = [...this.goodsAttr]

      if (this.form.skuList) {
        this.form.skuList.forEach(sku => {
          skuMap.set(sku.skuData, sku)
        })
      }
      this.goodsAttr.forEach((attr, index) => {
        const attrSku = [];
        attr.options.forEach((option) => {
          if (!option.name) {
            return
          }
          if (index === 0) {
            attrSku.push({ [attr.name]: option.name });
          } else {
            skus.forEach(it3 => {
              attrSku.push({ ...it3, [attr.name]: option.name })
            })
          }
        })
        skus = attrSku;
      })
      skus.forEach(it => {
        if (it) {
          it.skuData = JSON.stringify(it)
        }
      })
      skus.forEach(it => {
        let sku = skuMap.get(it.skuData);
        if (sku) {
          it.outSkuId = sku.outSkuId;
          it.price = sku.price;
          it.pic = sku.pic;
          it.inventory = sku.inventory;
          it.weight = sku.weight;
          it.originalPrice = sku.originalPrice;
          it.shareAccount = sku.shareAccount;
          it.shareIntegral = sku.shareIntegral;
          it.coding = sku.coding;
          it.id = sku.id;
        } else {
          it.outSkuId = null;
          it.price = 0;
          it.pic = null;
          it.inventory = 0;
          it.weight = 0;
          it.originalPrice = 0;
          it.shareAccount = 0;
          it.shareIntegral = 0;
          it.coding = null;
          it.id = null;
        }

      })
      this.form.goodsAttr = JSON.stringify(this.goodsAttr)
      this.form.skuList = skus
    },
    categoryChange(value) {
      if (Array.isArray(value)) {
        console.log(value.toString())
        this.form.productCategoryName = value.toString()
      } else {
        this.form.productCategoryName = null
      }

    },

    shopChange(value) {
      console.log(value);
   
      this.listKind(value);
    },
    onBrandChange(value) {
      this.form.brandName = value
    },
    getInfo(id) {
      getGoods(id).then(response => {

        this.form = response;
        const { tags } = response
        if (tags) {
          this.tags = tags.split(',');
        }

        this.albumPics = response.goodsImages;

        const { mealStartTime } = response
        if (mealStartTime) {
          this.rangeTime = [this.form.mealStartTime, this.form.mealEndTime];
        }

        const { morningTime } = response
        if (morningTime) {
          let a = morningTime.split('-');
          this.rangeMorning = [a[0], a[1]];
        }
        const { noonTime } = response
        if (noonTime) {
          let a = noonTime.split('-');
          this.rangeNoon = [a[0], a[1]];
        }
        const { nightTime } = response
        if (nightTime) {
          let a = nightTime.split('-');
          this.rangeNight = [a[0], a[1]];
        }
        if (this.form.goodsAttr) {
          this.goodsAttr = JSON.parse(this.form.goodsAttr)
        }
        if (this.form.buyType == 0) {
          this.buyFlag = true;
        } else {
          this.buyFlag = false;
        }

        this.listKind(this.form.shopId);
        this.refreshSku()
      });
    },
    listKind(val) {
      listKind({ shopId: val, status: "1" }).then(response => {
        this.kindList = response.rows;

      });
    },
    /**获取中心 */
    getShopTree(organId) {
      getShopTree(organId).then(response => {
        this.shopOptions = response.data;

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mealStartTime = this.rangeTime[0];
          this.form.mealEndTime = this.rangeTime[1];
          this.form.morningTime = this.rangeMorning.join('-');
          this.form.noonTime = this.rangeNoon.join('-');
          this.form.nightTime = this.rangeNight.join('-');
          this.form.tags = this.tags.join(',');
          if (this.albumPics) {
            this.form.goodsImages = this.albumPics;
          }
          if (this.form.categoryId && Array.isArray(this.form.categoryId)) {
            this.form.categoryId = this.form.categoryId.pop()
          }
          //商品价格没填时取sku的最低价
          if (!this.form.price) {
            this.form.price = Math.min.apply(Math, this.form.skuList.map(it => it.price))
          }
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            });
          }
          this.cancel();
        } else {
          if (this.form.name) {
            this.$alert('请填写规格价格', '提示', {
              confirmButtonText: '确定',
            });
          } else {
            this.$alert('请填写商品名称', '提示', {
              confirmButtonText: '确定',
            });
          }
        }
      });
    },
    cancel() {
      this.$tab.closeOpenPage({ path: '/goods/index' })
    },
    changeName(s, idx, val) {
      s.options[idx].name = val;
      if (s.options.length - 1 !== idx || s.options.length >= this.maxOptionNum) {
        return
      }
      s.options.push({ name: null })
    },
    addSkuSort() {
      this.goodsAttr.push({
        name: null,
        options: [{ name: null }]
      })
    },
    deleteSkuSort(idx) {
      this.goodsAttr.splice(idx);
    },
    deleteOption(s, idx) {
      s.options.splice(idx, 1);
    },
    changeBuy(val) {
      if (val == 0) {
        this.buyFlag = true;
      } else {
        this.buyFlag = false;
      }
    }
  }
}
</script>
